package routes

import (
	"database/sql"
	"web-service/controllers"
	"web-service/middleware"

	"github.com/gin-gonic/gin"
)

// SetupRouter 配置路由
func SetupRouter(db *sql.DB) *gin.Engine {
	r := gin.Default()

	// 允许跨域中间件
	r.Use(func(c *gin.Context) {
		c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
		c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
		c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With")
		c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT, DELETE")

		if c.Request.Method == "OPTIONS" {
			c.AbortWithStatus(204)
			return
		}

		c.Next()
	})

	// 初始化控制器
	authorController := &controllers.AuthorController{DB: db}
	tagController := &controllers.TagController{DB: db}
	userController := &controllers.UserController{DB: db}
	statsController := &controllers.StatsController{DB: db}
	excerptController := &controllers.BookExcerptController{DB: db}

	// 用户登录路由
	r.POST("/api/login", userController.Login)

	// 公开路由
	r.GET("/api/books", controllers.GetBooks)
	r.GET("/api/books/:id", controllers.GetBookByID)
	r.GET("/api/authors", authorController.GetAuthorList)
	r.GET("/api/authors/search", authorController.SearchAuthor)
	r.GET("/api/tags", tagController.GetTagList)
	r.GET("/api/tags/all", tagController.GetAllTags)
	r.GET("/api/stats", statsController.GetStats)

	// 需要认证的路由
	auth := r.Group("/api")
	auth.Use(middleware.JWT())
	{
		auth.POST("/books", controllers.AddBook)
		auth.PUT("/books/:id", controllers.UpdateBook)
		auth.POST("/authors", authorController.CreateAuthor)
		auth.PUT("/authors/:id", authorController.UpdateAuthor)
		auth.DELETE("/authors/:id", authorController.DeleteAuthor)
		auth.POST("/tags", tagController.CreateTag)
		auth.PUT("/tags/:id", tagController.UpdateTag)
		auth.DELETE("/tags/:id", tagController.DeleteTag)
		// 书摘相关路由
		auth.POST("/excerpts/book/:bookId", excerptController.CreateBookExcerpt)
		auth.PUT("/excerpts/:id", excerptController.UpdateBookExcerpt)
	}

	// 公开的书摘路由
	r.GET("/api/excerpts/book/:bookId", excerptController.GetBookExcerpts)

	return r
}
